package org.robot.scm.platform.monitor;

import com.alibaba.fastjson.JSONObject;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.robot.scm.platform.AbstractMonitor;
import org.robot.scm.pojos.BaseNotify;
import org.robot.scm.pojos.config.BaseConfig;
import org.robot.scm.pojos.enums.PlatformEnum;
import org.robot.scm.retry.SimpleRetryable;
import org.robot.scm.utils.AuthDecryptUtil;
import org.robot.scm.utils.JsonHelper;

/**
 * 破解e小天持续授权, 只需要实现read方法即可，无需后续操作
 *
 * @Author : Awn create on 2024/4/2 14:33
 */
@Slf4j
public class AuthDecryptMonitor extends AbstractMonitor {

    @Override
    public PlatformEnum getPlatform() {
        return PlatformEnum.EAUTH;
    }

    @Override
    public BaseNotify doMonitor(BaseConfig config) {
        new SimpleRetryable(20, 3000).retry(() -> this.read(config), Objects::nonNull);
        return null;
    }

    private Boolean read(BaseConfig config) {
        AuthDecryptUtil.baseUrl = config.getCurrentPlatform().getNoticeSrc();
        try {
            // 获取设备信息
            JSONObject deviceInfo = AuthDecryptUtil.getDeviceInfo();
            Integer pid = deviceInfo.getInteger("pid");
            String wxid = deviceInfo.getString("wxid");

            // 获取验证
            String checkToken = doAuth();

            // 4、获取机器进程信息
            JSONObject mres = AuthDecryptUtil.queryProcess(pid);
            String data = URLEncoder.encode(mres.getString("data"), StandardCharsets.UTF_8);
            String pcid = mres.getString("id");

            // 5、发起授权请求
            JSONObject ares = AuthDecryptUtil.executeAuth(wxid, pcid, data, checkToken);
            String token = ares.getString("token");
            String auth = ares.getString("auth");

            // 6、授权确认
            AuthDecryptUtil.confirmAuth(pid, token, auth);
        } catch (Exception e) {
            log.error("eauth failed, error: {}", e.getMessage());
            return null;
        }
        return Boolean.TRUE;
    }

    /**
     * 通过每次点击第一个按钮来碰运气
     */
    private String doAuth() {
        try {
            // 获取验证码
            JSONObject touchCapture = AuthDecryptUtil.touchCapture();

            // 点击正确的验证码
            return AuthDecryptUtil.clickCapture(touchCapture.getJSONArray("words"));
        } catch (Exception e) {
            return doAuth();
        }
    }

}
